import 'package:flutter/material.dart';

class ClipImage extends StatelessWidget {
  final String imagePath;
  final Offset startOffset;
  final double clipWidth;
  final double clipHeight;

  const ClipImage({
    Key? key,
    required this.imagePath,
    required this.startOffset,
    required this.clipWidth,
    required this.clipHeight,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: clipWidth,
      height: clipHeight,
      child: ClipRect(
        clipper: _ImageClipper(
          clipWidth: clipWidth,
          clipHeight: clipHeight,
        ),
        child: Stack(
          children: [
            Positioned(
              left: -startOffset.dx,
              top: -startOffset.dy,
              child: Image.asset(
                imagePath,
                fit: BoxFit.none,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ImageClipper extends CustomClipper<Rect> {
  final double clipWidth;
  final double clipHeight;

  _ImageClipper({
    required this.clipWidth,
    required this.clipHeight,
  });

  @override
  Rect getClip(Size size) {
    // 从左上角(0, 0)开始，创建指定宽度和高度的矩形裁剪区域
    return Rect.fromLTWH(0, 0, clipWidth, clipHeight);
  }

  @override
  bool shouldReclip(CustomClipper<Rect> oldClipper) {
    // 如果裁剪区域的尺寸发生变化，则需要重新裁剪
    if (oldClipper is _ImageClipper) {
      return clipWidth != oldClipper.clipWidth || clipHeight != oldClipper.clipHeight;
    }
    return false;
  }
}
